# -*- coding: utf-8 -*-
##############################################################################
#
#
##############################################################################

##############################################################################

import time
from report import report_sxw
import pooler
from osv import osv
from tools.translate import _
import random
from datetime import datetime
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
DATE_FORMAT = "%Y-%m-%d"

class Parser(report_sxw.rml_parse):
        
    def __init__(self, cr, uid, name, context):
        super(Parser, self).__init__(cr, uid, name, context=context)
        pool = pooler.get_pool(self.cr.dbname)
        self.cr = cr
        self.uid = uid
        
        self.localcontext.update({
#             'get_line':self.get_line,
#             'get_total_line':self.get_total_line,
#             'get_basic_allowance_line': self.get_another_payslip,
            'get_line_gross': self.get_line_gross,
            'get_line_net' : self.get_line_net,
            'get_line_deduction': self.get_line_deduction,
            'get_another_payslip':self.get_another_payslip,
            'get_datetime_now': self.get_datetime_now,
            'get_gross': self.get_gross,
            'get_total_deduction': self.get_total_deduction,
        })
        
    def get_line_gross(self, obj):
        payslip_line = self.pool.get('hr.payslip.line')
        rule_cate_obj = self.pool.get('hr.salary.rule.category')

        def get_recursive_parent(rule_categories):
            if not rule_categories:
                return []
            if rule_categories[0].parent_id:
                rule_categories.insert(0, rule_categories[0].parent_id)
                get_recursive_parent(rule_categories)
            return rule_categories

        res = []
        result = {}
        ids = []

        for id in range(len(obj)):
            ids.append(obj[id].id)
        if ids:
            self.cr.execute('''SELECT pl.id, pl.category_id FROM hr_payslip_line as pl \
                LEFT JOIN hr_salary_rule_category AS rc on (pl.category_id = rc.id) \
                WHERE pl.id in %s \
                AND rc.name in ('Basic','Allowance') \
                GROUP BY rc.parent_id, pl.sequence, pl.id, pl.category_id \
                ORDER BY pl.sequence, rc.parent_id''',(tuple(ids),))
            for x in self.cr.fetchall():
                result.setdefault(x[1], [])
                result[x[1]].append(x[0])
            for key, value in result.iteritems():
                rule_categories = rule_cate_obj.browse(self.cr, self.uid, [key])
                parents = get_recursive_parent(rule_categories)
                for line in payslip_line.browse(self.cr, self.uid, value):
                     res.append({
                        'rule_category': line.category_id.name,
                        'name': line.name,
                        'code': line.code,
                        'total': line.total,
                    })
        return res  
    
    def get_line_deduction(self, obj):
        payslip_line = self.pool.get('hr.payslip.line')
        rule_cate_obj = self.pool.get('hr.salary.rule.category')

        def get_recursive_parent(rule_categories):
            if not rule_categories:
                return []
            if rule_categories[0].parent_id:
                rule_categories.insert(0, rule_categories[0].parent_id)
                get_recursive_parent(rule_categories)
            return rule_categories

        res = []
        result = {}
        ids = []

        for id in range(len(obj)):
            ids.append(obj[id].id)
        if ids:
            self.cr.execute('''SELECT pl.id, pl.category_id FROM hr_payslip_line as pl \
                LEFT JOIN hr_salary_rule_category AS rc on (pl.category_id = rc.id) \
                WHERE pl.id in %s \
                AND rc.name in ('Deduction') \
                GROUP BY rc.parent_id, pl.sequence, pl.id, pl.category_id \
                ORDER BY pl.sequence, rc.parent_id''',(tuple(ids),))
            for x in self.cr.fetchall():
                result.setdefault(x[1], [])
                result[x[1]].append(x[0])
            for key, value in result.iteritems():
                rule_categories = rule_cate_obj.browse(self.cr, self.uid, [key])
                parents = get_recursive_parent(rule_categories)
                for line in payslip_line.browse(self.cr, self.uid, value):
                     res.append({
                        'rule_category': line.category_id.name,
                        'name': line.name,
                        'code': line.code,
                        'total': line.total,
                    })
        return res   
    
    def get_line_net(self, obj):
        payslip_line = self.pool.get('hr.payslip.line')
        rule_cate_obj = self.pool.get('hr.salary.rule.category')

        def get_recursive_parent(rule_categories):
            if not rule_categories:
                return []
            if rule_categories[0].parent_id:
                rule_categories.insert(0, rule_categories[0].parent_id)
                get_recursive_parent(rule_categories)
            return rule_categories

        res = []
        result = {}
        ids = []

        for id in range(len(obj)):
            ids.append(obj[id].id)
        if ids:
            self.cr.execute('''SELECT pl.id, pl.category_id FROM hr_payslip_line as pl \
                LEFT JOIN hr_salary_rule_category AS rc on (pl.category_id = rc.id) \
                WHERE pl.id in %s \
                AND rc.name in ('Net') \
                GROUP BY rc.parent_id, pl.sequence, pl.id, pl.category_id \
                ORDER BY pl.sequence, rc.parent_id''',(tuple(ids),))
            for x in self.cr.fetchall():
                result.setdefault(x[1], [])
                result[x[1]].append(x[0])
            for key, value in result.iteritems():
                rule_categories = rule_cate_obj.browse(self.cr, self.uid, [key])
                parents = get_recursive_parent(rule_categories)
                for line in payslip_line.browse(self.cr, self.uid, value):
                     res.append({
                        'rule_category': line.category_id.name,
                        'name': line.name,
                        'code': line.code,
                        'total': line.total,
                    })
        return res  
        
    def get_gross(self, obj):
        payslip_line = self.pool.get('hr.payslip.line')
        rule_cate_obj = self.pool.get('hr.salary.rule.category')

        def get_recursive_parent(rule_categories):
            if not rule_categories:
                return []
            if rule_categories[0].parent_id:
                rule_categories.insert(0, rule_categories[0].parent_id)
                get_recursive_parent(rule_categories)
            return rule_categories

        res = []
        result = {}
        ids = []

        for id in range(len(obj)):
            ids.append(obj[id].id)
        if ids:
            self.cr.execute('''SELECT pl.id, pl.category_id FROM hr_payslip_line as pl \
                LEFT JOIN hr_salary_rule_category AS rc on (pl.category_id = rc.id) \
                WHERE pl.id in %s \
                GROUP BY rc.parent_id, pl.sequence, pl.id, pl.category_id \
                ORDER BY pl.sequence, rc.parent_id''',(tuple(ids),))
            for x in self.cr.fetchall():
                result.setdefault(x[1], [])
                result[x[1]].append(x[0])
            for key, value in result.iteritems():
                rule_categories = rule_cate_obj.browse(self.cr, self.uid, [key])
                parents = get_recursive_parent(rule_categories)
                category_total = 0
                for line in payslip_line.browse(self.cr, self.uid, value):
                        category_total += line.total
                for line in payslip_line.browse(self.cr, self.uid, value):
                    if line.category_id.name == 'Gross':
                        return line.total
        return 0
    
    def get_total_deduction(self, obj):
        payslip_line = self.pool.get('hr.payslip.line')
        rule_cate_obj = self.pool.get('hr.salary.rule.category')

        def get_recursive_parent(rule_categories):
            if not rule_categories:
                return []
            if rule_categories[0].parent_id:
                rule_categories.insert(0, rule_categories[0].parent_id)
                get_recursive_parent(rule_categories)
            return rule_categories

        res = []
        result = {}
        ids = []
        total = 0
        for id in range(len(obj)):
            ids.append(obj[id].id)
        if ids:
            self.cr.execute('''SELECT pl.id, pl.category_id FROM hr_payslip_line as pl \
                LEFT JOIN hr_salary_rule_category AS rc on (pl.category_id = rc.id) \
                WHERE pl.id in %s \
                GROUP BY rc.parent_id, pl.sequence, pl.id, pl.category_id \
                ORDER BY pl.sequence, rc.parent_id''',(tuple(ids),))
            for x in self.cr.fetchall():
                result.setdefault(x[1], [])
                result[x[1]].append(x[0])
            for key, value in result.iteritems():
                rule_categories = rule_cate_obj.browse(self.cr, self.uid, [key])
                parents = get_recursive_parent(rule_categories)
                category_total = 0
                for line in payslip_line.browse(self.cr, self.uid, value):
                        category_total += line.total
                for line in payslip_line.browse(self.cr, self.uid, value):
                    if line.category_id.name == 'Deduction':
                        total += line.total
        return total
        
    
    def get_another_payslip(self):
            sql = '''
                SELECT pay_line.name,pay_line.amount 
                FROM hr_salary_rule_category cat inner join hr_payslip_line pay_line on cat.code = pay_line.code 
                WHERE cat.name in ('Net') and 
                pay_line.create_date::date  between '2013-01-01' and '2014-01-01'
            '''
            self.cr.execute(sql)
            return self.cr.dictfetchall()
    
    def get_datetime_now(self):
        return datetime.now()
#     def get_infomation(self):
        
#         return True
        
#     def get_condition(self,date):
#         if date >= '2013-01-01' and date <= '2014-01-01':
#             return True
#         else:
#             return False
#                     
#     def get_line(self,pay_line_ids):
#         res = []
#         result = {}
#         ids = []
#         rule_cate_obj = self.pool.get('hr.salary.rule.category')
#         payslip_line = self.pool.get('hr.payslip.line')
# 
#         def get_recursive_parent(rule_categories):
#             if not rule_categories:
#                 return []
#             if rule_categories[0].parent_id:
#                 rule_categories.insert(0, rule_categories[0].parent_id)
#                 get_recursive_parent(rule_categories)
#             return rule_categories
#         for line1 in pay_line_ids:
#             ids.append(line1.id)
#         sql = '''
#             SELECT pl.id, pl.category_id FROM hr_payslip_line pl 
#                 LEFT JOIN hr_salary_rule_category rc on (pl.category_id = rc.id) 
#                 WHERE pl.id in (%s) 
#                 and pl.name = 'Basic'
#                 GROUP BY rc.parent_id, pl.sequence, pl.id, pl.category_id 
#                 ORDER BY pl.sequence, rc.parent_id
#         '''%(','.join(map(str,ids)))
#         self.cr.execute(sql)
#         
#         for x in self.cr.fetchall():
#                 result.setdefault(x[1], [])
#                 result[x[1]].append(x[0])
#         for key, value in result.iteritems():
#             rule_categories = rule_cate_obj.browse(self.cr, self.uid, [key])
#             parents = get_recursive_parent(rule_categories)
#             category_total = 0
#             for line in payslip_line.browse(self.cr, self.uid, value):
#                 category_total += line.total
#             level = 0
#             for parent in parents:
#                 res.append({
#                     'rule_category': parent.name,
#                     'name': parent.name,
#                     'code': parent.code,
#                     'level': level,
#                     'total': category_total,
#                 })
#                 level += 1
#             for line in payslip_line.browse(self.cr, self.uid, value):
#                 res.append({
#                     'rule_category': line.name,
#                     'name': line.name,
#                     'code': line.code,  
#                     'total': line.total,
#                     'level': level
#                 })
#         
#         return res
#     
#     def get_total_line(self):
#         sql = '''
#             SELECT sum(pay_line.amount) amount
#             FROM hr_salary_rule_category cat inner join hr_payslip_line pay_line
#             on cat.code = pay_line.code 
#         '''
#         self.cr.execute(sql)
#         for line in self.cr.dictfetchall():
#             return line['amount']
#         return 0
#     
#     def get_line_deductions(self):
#         sql = '''
#             SELECT 1 as type, pay_line.name,pay_line.amount 
#             FROM hr_salary_rule_category cat inner join hr_payslip_line pay_line on cat.code = pay_line.code 
#             WHERE cat.name in ('Allowance') 
#             UNION 
#             SELECT 2 as type, pay_line.name,pay_line.amount 
#             FROM hr_salary_rule_category cat inner join hr_payslip_line pay_line on cat.code = pay_line.code 
#             WHERE cat.name in ('Net') and 
#             pay_line.create_date::date  between '2013-01-01' and '2014-01-01'
#         '''
#         self.cr.execute(sql)
#         return self.cr.dictfetchall()
#     
#     def get_total_line_deductions(self):
#         sql = '''
#             SELECT sum(pay_line.amount) amount
#             FROM hr_salary_rule_category cat inner join hr_payslip_line pay_line on cat.code = pay_line.code 
#             WHERE cat.name ='DED' 
#         '''
#         self.cr.execute(sql)
#         for line in self.cr.dictfetchall():
#             return line['amount']
#         return 0
   
    
    
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: